package com.boarsoft.boar.deploy.file;

import java.io.File;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Lazy;

import com.boarsoft.agent.AgentService;
import com.boarsoft.bean.ReplyInfo;
import com.boarsoft.boar.BaseConfig;
import com.boarsoft.boar.deploy.bean.BuildInstParam;
import com.boarsoft.common.Util;
import com.boarsoft.flow.core.bean.ProcessHandler;
import com.boarsoft.rpc.core.RpcContext;

public class UnzipFilePH implements ProcessHandler {
	private static final Logger log = LoggerFactory.getLogger(UnzipFilePH.class);

	@Autowired
	@Lazy(value = true)
	@Qualifier("agentX")
	protected AgentService agentX;

	protected String shell;

	@Override
	public Object process(String entry, Object data, Throwable throwable) throws Throwable {
		BuildInstParam p = (BuildInstParam) data;
		// 部署包在目标节点上，相对于AgentConfig.FILE_PATH的路径
		String fn = new File(p.getPackPath()).getName();
		String to = new File(p.getTargetPath()).getParent();// 解压到部署目录
		String axa = new StringBuilder().append(p.getIp()).append(":")//
				.append(BaseConfig.AGENTX_PORT).toString();
		log.info("Ask {} unzip {} to {}", axa, fn, to);
		RpcContext.specify2(axa);
		try {
			ReplyInfo<Object> ro = null;
			if (Util.strIsEmpty(shell)) {
				ro = agentX.unzip(fn, to);
			} else {
				// 执行 AgentConfig.SHELL_PATH下 的 解压缩脚本，传递应用的部署目录 dp 作为参数
				ro = agentX.executeShell(shell, new String[] { fn, to });
			}
			if (ro.isSuccess()) {
				log.info("AgentX {} unzip {} to {} successfully", //
						axa, fn, to);
				return data;
			}
			throw new Exception(new StringBuilder("AgentX ").append(axa)//
					.append(" unzip ").append(fn).append(" to ").append(to)//
					.append(" failed, reason: ")//
					.append(ro.getData()).toString());
		} finally {
			RpcContext.specify2(null);
		}
	}

	public String getShell() {
		return shell;
	}

	public void setShell(String shell) {
		this.shell = shell;
	}
}